/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*   File:      TableButtonFunction.cpp
*   Author:    刘洋兵
*   Function:  为显示表的最后一列添加不同功能的按键，并实现对应功能
*   Time:      2025-09-09
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "TableButtonFunction.h"

/**
 * @brief  TableButtonFunction的构造函数
 * @param  parent 父对象
 */
TableButtonFunction::TableButtonFunction(QWidget *parent)
    : QWidget(parent)
{
    Alter_Data = new AlterDataDialog(this);
    connect(this, &TableButtonFunction::sendAlterUi, Alter_Data, &AlterDataDialog::display_specified_ViewWindow);
    connect(Alter_Data, &AlterDataDialog::senddatalist, this, &TableButtonFunction::alterUIData);
    connect(Alter_Data, &AlterDataDialog::sendadddatalist, this, &TableButtonFunction::alterAddData);
}

/**
 * @brief  设置显示表最后一列的按键以及对应功能
 * @param  model 模型类QStandardItemModel对象指针
 * @param  tableView 控件QTableView的对象指针
 * @param  IconNum 需要添加哪些按键功能的索引列表
 * @param  DataCount 显示控件中每次添加数据的行数
 */
void TableButtonFunction::addButton(QStandardItemModel *model,
                                    QTableView *tableView,
                                    const QList<IconNumber>& IconNum,
                                    const int& DataCount)
{
    AddMyPushButton setButton;
    int beginrow = 0;
    if(model->rowCount()!=DataCount)
    {
        beginrow = model->rowCount()-DataCount;  //添加数据开始的行索引
    }
    for(int row = 0; row < DataCount; row++) {
        QWidget *widget = new QWidget(this);
        QHBoxLayout* vLay = new QHBoxLayout(widget);
        for (int num = 0;num < IconNum.count(); num++) {
            QPushButton *btn = new QPushButton(widget);
            setButton.setButton(btn, IconNum[num]);
            if(IconNum[num]==IconNumber::Icon_Delete)
            {
                btn->setEnabled(false);
                connect(btn, &QPushButton::clicked, this, [=]{
                    this->clearselecteditem(tableView);
                });
            }
            else if(IconNum[num]==IconNumber::Icon_Edit)
            {
                connect(btn, &QPushButton::clicked, this, [=]{
                    this->editselecteditem(tableView);
                });
            }
            else if(IconNum[num]==IconNumber::Icon_Detail)
            {
                connect(btn, &QPushButton::clicked, this, [=]{
                    this->detaileddatashows(tableView);
                });
            }
            else if(IconNum[num]==IconNumber::Icon_Refresh)
            {
                connect(btn, &QPushButton::clicked, this, [=]{
                    //this->AddClicked();
                });
            }
            else if(IconNum[num]==IconNumber::Icon_Positioning)
            {
                connect(btn, &QPushButton::clicked, this, [=]{
                    this->agvrelocation(tableView);
                });
            }
            else if(IconNum[num]==IconNumber::Icon_Cancel)
            {
                connect(btn, &QPushButton::clicked, this, [=]{
                    this->canceltask(tableView);
                });
            }
            else if(IconNum[num]==IconNumber::Icon_Pause)
            {
                btn->setProperty("iconName", "pause.png");
                connect(btn, &QPushButton::clicked, this, [=]{
                    this->taskpauseorstart(tableView);
                });
            }
            else if(IconNum[num]==IconNumber::Icon_Replace_Task)
            {
                // 任务接替
                connect(btn, &QPushButton::clicked, this, [=]{
                    this->taskReplacement(tableView);
                });
            }
            else if(IconNum[num]==IconNumber::Icon_Replace)
            {
                // 需要换车
                connect(btn, &QPushButton::clicked, this, [=]{
                    this->AGVReplacement(tableView);
                });
            }
            else if(IconNum[num]==IconNumber::Icon_Manual)
            {
                // 人工辅助完成
                connect(btn, &QPushButton::clicked, this, [=]{
                    this->Manual(tableView);
                });
            }
            vLay->addWidget(btn);
        }
        vLay->setAlignment(Qt::AlignCenter);
        vLay->setContentsMargins(0,0,0,0);
        widget->setLayout(vLay);
        int lastCol = model->columnCount()-1;
        tableView->setIndexWidget(model->index(beginrow+row, lastCol), widget);
    }
}

/**
* @brief  删除数据
* @param  tableView 控件QTableView对象指针
*/
void TableButtonFunction::clearselecteditem(QTableView *tableView)
{
    QPushButton* pu_btn = dynamic_cast<QPushButton*>(this->sender());
    if(pu_btn == nullptr)
    {
        delete pu_btn;
        return;
    }
    QString tablename = tableView->objectName();
    int x = pu_btn->parentWidget()->pos().x();
    int y = pu_btn->parentWidget()->pos().y();
    QModelIndex index = tableView->indexAt(QPoint(x,y));
    int row = index.row();
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableView->model());
    // 添加下发数据库删除的语句
    bool is_clear = false;
    //发送数据类
    QMap<QString, QVariant> infomap;
    QMap<QString, QVariant> dataMap;
    int function_code = 0;
    if(tablename == "tableView_vehicle_profile") {
        infomap["table_name"] = "tb_vehicle_profile";
        infomap["operation_type"] = 2;
        int vehicle_id = model->data(model->index(row, 0)).toInt();
        dataMap["vehicle_id"] = vehicle_id;
        dataMap["vehicle_name"] = "";
        dataMap["brand"] = 1;
        dataMap["ip_address"] = "";
        dataMap["port"] = 8080;
        dataMap["vehicle_type"] = 1;
        dataMap["battery_type"] = 1;
        dataMap["charge_max_current"] = 0;
        dataMap["charge_max_voltage"] = 0;
        dataMap["is_available"] = 0;
        function_code = 202;
        is_clear = true;
    }

    else if (tablename == "tableView_map_config") {
        infomap["table_name"] = "tb_map_config";
        infomap["operation_type"] = 2;
        QString map_id = model->data(model->index(row, 0)).toString();
        dataMap["map_code"] = map_id;
        dataMap["map_name"] = "";
        dataMap["workshop_name"] = "";
        dataMap["map_url"] = "";
        dataMap["origin_x"] = 0;
        dataMap["origin_y"] = 0;
        dataMap["origin_z"] = 0;
        dataMap["map_scale"] = 0;
        dataMap["map_status"] = 0;
        dataMap["map_type"] = 0;
        function_code = 208;
        is_clear = true;
    }
    else if (tablename == "tableView_district_seats") {
        infomap["table_name"] = "tb_district_seats";
        infomap["operation_type"] = 2;
        int district_seat_id = model->data(model->index(row, 0)).toInt();
        dataMap["district_seat_id"] = district_seat_id;
        dataMap["map_code"] = "";
        dataMap["district_name"] = "";
        dataMap["district_type"] = 0;
        dataMap["seat"] = "";
        function_code = 205;
        is_clear = true;
    }
    else if (tablename == "tableView_nodes") {
        infomap["table_name"] = "tb_nodes";
        infomap["operation_type"] = 2;
        QString node_id = model->data(model->index(row, 0)).toString();
        dataMap["node_id"] = node_id;
        dataMap["map_code"] = "";
        dataMap["node_name"] = "";
        dataMap["node_type"] = 1;
        dataMap["node_x"] = 0;
        dataMap["node_y"] = 0;
        dataMap["node_z"] = 0;
        dataMap["angle"] = 0;
        dataMap["relocate_pos"] = 1;
        function_code = 207;
        is_clear = true;
    }
    else if (tablename == "tableView_paths") {
        infomap["table_name"] = "tb_paths";
        infomap["operation_type"] = 2;
        int path_id = model->data(model->index(row, 0)).toInt();
        dataMap["path_id"] = path_id;
        dataMap["map_code"] = "";
        dataMap["path_name"] = "";
        dataMap["start_name"] = "";
        dataMap["goal_name"] = "";
        dataMap["control_1_x"] = 0;
        dataMap["control_1_y"] = 0;
        dataMap["control_2_x"] = 0;
        dataMap["control_2_y"] = 0;
        dataMap["direction"] = 0;
        dataMap["forward_path_angle"] = 0;
        dataMap["forward_path_angle"] = 0;
        dataMap["path_length"] = 0;
        dataMap["path_width"] = 0;
        function_code = 209;
        is_clear = true;
    }

    else if (tablename == "tableView_tasks") {
        // 停止定时刷新
        MyDatabase::getInstance().stopTimer("tb_tasks");
        infomap["table_name"] = "tb_tasks";
        infomap["operation_type"] = 2;
        int task_id = model->data(model->index(row, 0)).toInt();
        dataMap["task_id"] = task_id;
        dataMap["task_status"] = 4;
        function_code = 201;
        is_clear = true;
    }

    else if(tablename == "tableView_vehicle_action_set") {
        infomap["table_name"] = "tb_vehicle_action_set";
        infomap["operation_type"] = 2;
        int action_code = model->data(model->index(row, 0)).toInt();
        dataMap["action_code"] = action_code;
        dataMap["action_name"] = "";
        dataMap["action_type"] = 1;
        dataMap["action_height"] = 0;
        dataMap["action"] = 1;
        dataMap["immediate_status"] = 1;
        dataMap["qr_code_id"] = 0;
        dataMap["rotate_angle"] = 0;
        dataMap["goods_angle"] = 0;
        dataMap["drop_status"] = 0;
        dataMap["shelves_name"] = "";
        dataMap["function_code"] = "";
        dataMap["exit_pose"] = "";
        dataMap["speed"] = 0;
        function_code = 204;
        is_clear = true;
    }
    else if(tablename == "tableView_action_group") {
        infomap["table_name"] = "tb_action_group";
        infomap["operation_type"] = 2;
        int group_id = model->data(model->index(row, 0)).toInt();
        dataMap["action_group_id"] = group_id;
        dataMap["action_group_name"] = "";
        dataMap["start_action_code"] = 1;
        dataMap["end_action_code"] = 1;
        function_code = 203;
        is_clear = true;
    }
    if(is_clear)
    {
        if(CommandSendorReceive::getInstance().isExecute("提示","确认删除该条数据"))
        {
            // 打包发送json数据结构
            CommandSendorReceive::getInstance().sendCommand(dataMap, infomap, function_code, true);
            // 删除Table表数据
            model->removeRow(row);
            // 恢复定时器
            MyDatabase::getInstance().startTimer("tb_tasks");
        }
    }

}

/**
* @brief  修改数据
* @param  tableView 控件QTableView对象指针
*/
void TableButtonFunction::editselecteditem(QTableView *tableView)
{
    QPushButton* pu_btn = dynamic_cast<QPushButton*>(this->sender());
    if(pu_btn == nullptr)
    {
        delete pu_btn;
        return;
    }

    QModelIndex index = tableView->indexAt(pu_btn->parentWidget()->pos());
    int row = index.row();

    QString Tablename = tableView->objectName();
    emit sendAlterUi(tableView, row, 3);
}

/**
* @brief  显示详细信息
* @param  tableView 控件QTableView对象指针
*/
void TableButtonFunction::detaileddatashows(QTableView *tableView)
{
    QPushButton* pu_btn = dynamic_cast<QPushButton*>(this->sender());
    if(pu_btn == nullptr)
    {
        delete pu_btn;
        return;
    }
    int x = pu_btn->parentWidget()->pos().x();
    int y = pu_btn->parentWidget()->pos().y();
    QModelIndex index = tableView->indexAt(QPoint(x,y));
    int row = index.row();
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableView->model());

    // 获取整行数据
    for(int col = 0; col < model->columnCount()-1; ++col) {
        QModelIndex cellIndex = model->index(row, col);
        qDebug() << "行" << row << "列" << col << "数据:"
                 << model->data(cellIndex).toString();
    }
}

/**
* @brief  注销任务
* @param  tableView 控件QTableView对象指针
*/
void TableButtonFunction::canceltask(QTableView *tableView)
{
    QPushButton* pu_btn = dynamic_cast<QPushButton*>(this->sender());
    if(pu_btn == nullptr)
    {
        delete pu_btn;
        return;
    }

    // 暂停tb_tasks表实时刷新的定时器
    MyDatabase::getInstance().stopTimer("tb_tasks");

    int x = pu_btn->parentWidget()->pos().x();
    int y = pu_btn->parentWidget()->pos().y();
    QModelIndex index = tableView->indexAt(QPoint(x,y));
    int row = index.row();
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableView->model());
    QString task_id = model->data(model->index(row, 0)).toString();
    QString sql = QString("select vehicle_id from tb_tasks where task_id = %1").arg(task_id);
    QList<QStringList> dataList = MyDatabase::getInstance().query_table(sql);
    int vehicle_id = dataList[0][0].toInt();
    //发送数据类
    QMap<QString, QVariant> infomap;
    QMap<QString, QVariant> dataMap;
    infomap["vehicle_id"] = vehicle_id;

    if(CommandSendorReceive::getInstance().isExecute("提示","确认注销该条任务"))
    {
        // 打包成json数据结构
        CommandSendorReceive::getInstance().sendCommand(dataMap, infomap, 306, false);
        // 删除当前行
        model->removeRow(row);
        // 开启tb_tasks表实时刷新的定时器
        MyDatabase::getInstance().startTimer("tb_tasks");
    }

}

/**
* @brief  AGV重定位
* @param  tableView 控件QTableView对象指针
*/
void TableButtonFunction::agvrelocation(QTableView *tableView)
{
    QPushButton* pu_btn = dynamic_cast<QPushButton*>(this->sender());
    if(pu_btn == nullptr)
    {
        delete pu_btn;
        return;
    }
    QString tablename = tableView->objectName();
    int x = pu_btn->parentWidget()->pos().x();
    int y = pu_btn->parentWidget()->pos().y();
    QModelIndex index = tableView->indexAt(QPoint(x,y));
    int row = index.row();

    emit sendtoAPIdisplay(tableView, 0 , 311 , row);
}

/**
* @brief  AGV暂停或继续
* @param  tableView 控件QTableView对象指针
*/
void TableButtonFunction::taskpauseorstart(QTableView *tableView)
{
    QPushButton* pu_btn = dynamic_cast<QPushButton*>(this->sender());
    if(pu_btn == nullptr)
    {
        delete pu_btn;
        return;
    }

    int function_code = 304;
    QString iconName = pu_btn->property("iconName").toString();

    int x = pu_btn->parentWidget()->pos().x();
    int y = pu_btn->parentWidget()->pos().y();
    QModelIndex index = tableView->indexAt(QPoint(x,y));
    int row = index.row();
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableView->model());
    int vehicle_id = model->data(model->index(row, 0)).toInt();
    //发送数据类
    QMap<QString, QVariant> infomap;
    QMap<QString, QVariant> dataMap;
    infomap["vehicle_id"] = vehicle_id;
    //打包成json数据结构

    if(iconName == "pause.png")
    {
        if(CommandSendorReceive::getInstance().isExecute("提示","确认暂停小车"))
        {
            function_code = 304;
            QIcon icon_pause = QIcon(":/Icon/image/continue.png");
            pu_btn->setProperty("iconName", "continue.png");
            pu_btn->setIcon(icon_pause);
            CommandSendorReceive::getInstance().sendCommand(dataMap, infomap, function_code, false);
        }
    }
    else if(iconName == "continue.png")
    {
        if(CommandSendorReceive::getInstance().isExecute("提示","确认小车继续"))
        {
            function_code = 305;
            QIcon icon_pause1 = QIcon(":/Icon/image/pause.png");
            pu_btn->setProperty("iconName", "pause.png");
            pu_btn->setIcon(icon_pause1);
            CommandSendorReceive::getInstance().sendCommand(dataMap, infomap, function_code, false);
        }
    }

}

/**
* @brief  获取修改的数据修改到ui中
* @param  table 控件QTableView对象指针
* @param  listdata 修改的数据列表
* @param  index table行索引
*/
void TableButtonFunction::alterUIData(QTableView* table,
                                      const QStringList& listdata,
                                      const int& index)
{
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(table->model());
    int columns = model->columnCount();
    int row = index;
    for (int col = 0; col < columns-1; col++) {
        QModelIndex index = model->index(row, col);
        model->setData(index, listdata[col], Qt::EditRole);
    }
}

/**
* @brief  获取到需要发送添加数据的数据
* @param  table 控件QTableView对象指针
* @param  listdata 修改的数据列表
* @param  IconList 图标索引列表
*/
void TableButtonFunction::alterAddData(QTableView* table,
                                       const QStringList& listdata,
                                       const QList<IconNumber>& IconList)
{
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(table->model());
    int columns = model->columnCount();
    int lastrow = model->rowCount();
    model->setRowCount(lastrow+1);
    for (int col = 0; col < columns-1; col++) {
        model->setData(model->index(lastrow, col), listdata[col]);
        model->setData(model->index(lastrow, col), Qt::AlignCenter, Qt::TextAlignmentRole);
    }
    addButton(model, table, IconList ,1);
}

/**
* @brief  获取添加界面的序号，发送显示界面
* @param  table 控件QTableView对象指针
* @param  index table行索引
* @param  operation_type 功能码
*/
void TableButtonFunction::AddViewWindow(QTableView* table,
                                        const int& index,
                                        const int& operation_type)
{
    emit sendAlterUi(table, index, operation_type);
}

/**
* @brief  中转平台，任务接替
* @param  tableView 控件QTableView对象指针
*/
void TableButtonFunction::taskReplacement(QTableView *tableView)
{
    QPushButton* pu_btn = dynamic_cast<QPushButton*>(this->sender());
    if(pu_btn == nullptr)
    {
        delete pu_btn;
        return;
    }
    int x = pu_btn->parentWidget()->pos().x();
    int y = pu_btn->parentWidget()->pos().y();
    QModelIndex index = tableView->indexAt(QPoint(x,y));
    int row = index.row();
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableView->model());
    int taskId = model->data(model->index(row, 0)).toInt();
    emit sendAGV_task(0,taskId);
}

/**
* @brief  子任务，需要换车
* @param  tableView 控件QTableView对象指针
*/
void TableButtonFunction::AGVReplacement(QTableView *tableView)
{
    QPushButton* pu_btn = dynamic_cast<QPushButton*>(this->sender());
    if(pu_btn == nullptr)
    {
        delete pu_btn;
        return;
    }

    // 暂停tb_tasks_error数据实时刷新的定时器
    MyDatabase::getInstance().stopTimer("tb_tasks_error");

    int x = pu_btn->parentWidget()->pos().x();
    int y = pu_btn->parentWidget()->pos().y();
    QModelIndex index = tableView->indexAt(QPoint(x,y));
    int row = index.row();
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableView->model());
    QString sourceTaskId = model->data(model->index(row, 1)).toString();

    //发送数据类
    QMap<QString, QVariant> infomap;
    QMap<QString, QVariant> dataMap;

    infomap["sourceTaskId"] = sourceTaskId;

    if(CommandSendorReceive::getInstance().isExecute("提示","确认需要更换车辆"))
    {
        CommandSendorReceive::getInstance().sendCommand(dataMap, infomap, 103, false);

        QString msg = QString("任务%1更换车辆").arg(sourceTaskId);
        LOG_INFO(msg);
    }

    // tb_tasks_error
    MyDatabase::getInstance().startTimer("tb_tasks_error");
}


/**
* @brief  子任务，人工辅助完成
* @param  tableView 控件QTableView对象指针
*/
void TableButtonFunction::Manual(QTableView *tableView)
{
    QPushButton* pu_btn = dynamic_cast<QPushButton*>(this->sender());
    if(pu_btn == nullptr)
    {
        delete pu_btn;
        return;
    }
    // 暂停tb_tasks_error数据实时刷新的定时器
    MyDatabase::getInstance().stopTimer("tb_tasks_error");

    int x = pu_btn->parentWidget()->pos().x();
    int y = pu_btn->parentWidget()->pos().y();
    QModelIndex index = tableView->indexAt(QPoint(x,y));
    int row = index.row();
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(tableView->model());
    QString TaskName = model->data(model->index(row, 2)).toString();

    //发送数据类
    QMap<QString, QVariant> infomap;
    QMap<QString, QVariant> dataMap;

    infomap["task_name"] = TaskName;
    infomap["task_status"] = 4;

    if(CommandSendorReceive::getInstance().isExecute("提示","确认人工已经完成辅助操作"))
    {
        // 确定逻辑
        CommandSendorReceive::getInstance().sendCommand(dataMap, infomap, 102, false);
        QString msg = QString("人工已经辅助完成任务:%1").arg(TaskName);
        LOG_INFO(msg);
    }

    // 启动tb_tasks_error数据刷新定时器
    MyDatabase::getInstance().startTimer("tb_tasks_error");
}


